<?php
class CMRPageShowMostViewed extends CMRPage
{
	private $keywords = array();
	
	private $displayLimit = 20;
	private $displayStart = 0;
	
	public function __construct($database)
	{
		parent::__construct($database);
		$this->keywords = explode(' ',$_POST['searchText']);
//		print_r ($this->keywords);
	}
	
	protected function getResources()
	{
		$resources = array();
		$totals = array();
		
		$date = new DateTime("now");
		$date = $date->modify("-7 days");
		
		$sql = "SELECT ResourceID, COUNT(*) AS Total ";
		$sql .= "FROM ViewedResources ";
		$sql .= "GROUP BY ResourceID ";
		$sql .= "ORDER BY Total DESC ";
		$sql .= "LIMIT 20";
		//		echo $sql."<br>\n";
		
/*		$sql =  "SELECT * FROM Resources ";
		$sql .= "WHERE DeletedBy = '0' AND StatusTypeID = '3' AND CreatedWhen > '".$date->format("Y-m-d H:i")."'";
		$sql .= "ORDER BY CreatedWhen DESC";*/
		$this->Database->ExecuteSQL($sql);
		while($row = $this->Database->getRow())
		{
//			echo "creating resource ".$row['ResourceID']."<br>\n";
			$resource = new Resource($this->Database->Recopy(),$row['ResourceID']);
//			echo "created resource ".$resource->getResourceID()."<br>\n";
			$resource->setCurrentUserGroup($this->userGroup);
			$resource->setViews($row['Total']);
			//			$resource->loadData($row['ResourceID'],$row['ResourceTitle'],$row['ResourceDescription'],$row['ResourceTypeID'],"","",,,,);
			array_push($resources,$resource);
		}
				
		return $resources;
	}
	
	protected function getContentsDiv()
	{
		$script = new EditDeleteFormScript();
		$html = $script->getHTML();
		
		$category = new Hidden();
		$category->setName("ResourceID");
		$html .= $category->getHTML();
		
		$hidden = new Hidden(); // just used for ViewFile so fileID can be passed by POST
		$hidden->setName("FileID");
		$html .= $hidden->getHTML();
		
		$hidden = new Hidden(); // just used for ViewFile so fileID can be passed by POST
		$hidden->setName("DBTableName");
		$html .= $hidden->getHTML();
		
		
	
		if(($this->userGroup=="Editors")||($this->userGroup=="Supervisors"))
		{
			$hidden = new Hidden();
			$hidden->setName("SubAction");
			$html .= $hidden->getHTML();
		}
		
		$html .= "<div id=\"content\">\n";
		$html .= "<h1>Most Viewed Resources</h1>\n";
		
		$sectionsPanel = new SectionsPanel('');
		$html .= $sectionsPanel->getHTML();
		
		$shortcutPanel = new ShortcutPanel('');
		$html .= $shortcutPanel->getHTML();
		
		$html .= "<p>This page shows the 20 most viewed resources.</p>";
		
		$resources = $this->getResources();
		if(count($resources)==0)$html .= "<p>There are currently no most viewed resources  (as if ...) </p>\n";
		foreach ($resources as $resource)
		{
//			echo "ShowMostViewed - resourceID = ".$resource->getResourceID."<br>\n";
			$html .= $resource->getSummaryHTML();
		}
				
		$html .= "</div>\n";
		return $html;
	}
	
}